package com.alex.algorithm.medium;

import com.alex.algorithm.easy.LinkedListNode;

public class RemoveNthNodeFromEndOfLinkedList {
    public static void main(String[] args) {
        LinkedListNode n1 = new LinkedListNode();
        n1.setVal(1);
        LinkedListNode n2 = new LinkedListNode();
        n1.setNext(n2);
        n2.setVal(2);
        LinkedListNode n22 = new LinkedListNode();
        n22.setVal(3);
        n2.setNext(n22);
        LinkedListNode n3 = new LinkedListNode();
        n3.setVal(4);
        n22.setNext(n3);
        LinkedListNode head = removeNth(n1, 2);


        while (head.getNext() != null) {
            System.out.println(head);
            head = head.getNext();
        }
    }

    public static LinkedListNode removeNth(LinkedListNode node, int n) {
        LinkedListNode dummyNode = new LinkedListNode();
        dummyNode.setNext(node);
        LinkedListNode left = dummyNode;
        LinkedListNode right = dummyNode;
        for (int i = 0; i < n+1; ++i) {
            right = right.getNext();
        }
        while (right != null) {
            left = left.getNext();
            right = right.getNext();
        }
        left.setNext(left.getNext().getNext());
        return dummyNode.getNext();
    }
}
